package cn.pzhu.jspdb.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class AuthorizeFilter
 */
public class AuthorizeFilter implements Filter {

    /**
     * Default constructor. 
     */
    public AuthorizeFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest)req;
		HttpServletResponse response=(HttpServletResponse)rsp;
		String url=request.getRequestURL().toString();
		String uri=request.getRequestURI();
		System.out.println("URL:"+url);
		System.out.println("URI:"+uri);
		
		String contextPath=request.getContextPath();
		System.out.println("ContextPath:"+contextPath);
		String servletContext=request.getServletContext().getContextPath();
		System.out.println("ContextPath:"+servletContext);
		
		HttpSession session=request.getSession();
		if(session.getAttribute("CUR_USER")!=null){
			chain.doFilter(req, rsp);
		}else{
			String loginUrl=contextPath+"/login.jsp";
			response.sendRedirect(loginUrl);
		}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
